﻿using Cysharp.Threading.Tasks;
using Internal;
using KuiHuaBaoDian.Services.Asset;
using Runtime.Services.Audio;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;

public sealed class DFR_Audio : IDFR_AudioInternal {

    private DFR_AudioMixer m_Mixer;
    public DFR_AudioMixer Mixer => m_Mixer;

    private DFR_AudioMixer m_MusicMixer;
    public DFR_AudioMixer MusicMixer => m_MusicMixer;

    private DFR_AudioMixer m_SFXMixer;
    public DFR_AudioMixer SFXMixer => m_SFXMixer;

    private DFR_AudioMixer m_UIMixer;
    public DFR_AudioMixer UIMixer => m_UIMixer;

    async UniTask IDFR_AudioInternal.SetMixer(AssetReference mixerAssetReference, AssetReference musicMixerAssetReference, AssetReference sfxMixerAssetReference, AssetReference uiMixerAssetReference) {
        var task1 = LoadMixer(mixerAssetReference).ContinueWith(mixer => m_Mixer = mixer);
        var task2 = LoadMixer(musicMixerAssetReference).ContinueWith(mixer => m_MusicMixer = mixer);
        var task3 = LoadMixer(sfxMixerAssetReference).ContinueWith(mixer => m_SFXMixer = mixer);
        var task4 = LoadMixer(uiMixerAssetReference).ContinueWith(mixer => m_UIMixer = mixer);
        await UniTask.WhenAll(task1, task2, task3, task4);
    }

    private async UniTask<DFR_AudioMixer> LoadMixer(AssetReference assetReference) {
        if (assetReference.RuntimeKeyIsValid()) {
            var runtimeKey = assetReference.RuntimeKey;
            var locationHandle = Addressables.LoadResourceLocationsAsync(runtimeKey);
            await locationHandle.ToUniTask();
            string assetKey;
            if (locationHandle.Status == AsyncOperationStatus.Succeeded && locationHandle.Result.Count > 0) {
                assetKey = locationHandle.Result[0].PrimaryKey;
                Addressables.Release(locationHandle);
            } else {
                UnityEngine.Debug.LogError("Failed to load resource locations for GUID: " + runtimeKey);
                return null;
            }
            var handle = await AssetService.Instance.Load<DFR_AudioMixer>(AssetRequest.Instantiate(assetKey), cacheGroup: nameof(DFR_Audio));
            if (handle == AssetHandle.None) {
                return null;
            }
            return handle.Content;
        }
        return null;
    }
}

namespace Internal {

    public interface IDFR_AudioInternal {

        UniTask SetMixer(AssetReference mixerAssetReference, AssetReference musicMixerAssetReference, AssetReference sfxMixerAssetReference, AssetReference uiMixerAssetReference);
    }
}